import serve from './request.js';

var payItemFun = function(payType, payId, jumpFile = '') {
	uni.showLoading({
		title: '唤起支付中···',
		mask: true
	});
	serve.request({
		url: '/order/pay/wechat',
		data: {
			appkey: uni.getStorageSync('appkey'),
			'access-token': uni.getStorageSync('access-token'),
			data_id: payId,
			data_type: payType
		}
	}).then(res => {
		uni.hideLoading();
		if (res.code != 200) {
			uni.showToast({
				title: res.message,
				icon: 'none'
			});
			return;
		}
		let payId = res.data.payId;
		let payConfig = res.data.payConfig;
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: payConfig.timeStamp,
			nonceStr: payConfig.nonceStr,
			package: payConfig.package,
			signType: payConfig.signType,
			paySign: payConfig.paySign,
			success: function(res) {
				queryPayResult(payType, payId, jumpFile);
				return;
			},
			fail: function(err) {
				uni.showToast({
					title: '放弃支付',
					icon: 'none',
					success() {
						if(serve.apiUrl() == 'http://hdsq.cn/api'){
							queryPayResult(payType, payId, jumpFile);
							return ;
						}
						if(jumpFile != '') {
							setTimeout(function() {
								uni.navigateBack({
								    delta: 1
								});
							}, 2000);
						}
					}
				});
				return;
			}
		})
	});
	return;
};
var queryPayResult = function(payType, payId, jumpFile = '', num = 20) {
	var _self = this;
	uni.showLoading({
		title: '支付结果查询中···',
		mask: true
	});
	if(num <= 0) {
		uni.showToast({
			title: '未接受到支付成功请求，请联系店铺工作人员！',
			icon: 'none',
			success() {
				uni.navigateBack({
				    delta: 1
				});
			}
		});
		return ;
	}
	setTimeout(function() {
		serve.request({
			url: '/payservice/query-pay',
			data:{
				appkey: uni.getStorageSync('appkey'),
				payType: payType,
				payId: payId,
			}
		}).then(res => {
			if(res.data.payStatus == 1) {
				uni.showToast({
					title: '支付成功',
					icon: 'none',
					success() {
						if(jumpFile != '') {
							console.info(jumpFile);
							setTimeout(function() {
								uni.redirectTo({
									url: jumpFile
								});
							}, 2000)
						}
					}
				});
			} else {
				num --;
				queryPayResult(payType, payId, jumpFile, num);
			}
		});
	}, 1500);
};


module.exports = {
    payItemFun: payItemFun,
    queryPayResult : queryPayResult,
};
